<template>
  <div class="school-manager-page">
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <a-card :bordered="false">
        <a-row :gutter="16" align="middle">
          <a-col :span="8">
            <a-select
              v-model:value="searchForm.schoolId"
              placeholder="请选择学校（可选）"
              style="width: 100%"
              show-search
              allow-clear
              :filter-option="filterSchoolOption"
              @change="handleSchoolChange"
            >
              <a-select-option v-for="school in schoolList" :key="school.id" :value="school.id">
                {{ school.schoolName }}-{{ school.campuses }}
              </a-select-option>
            </a-select>
          </a-col>

          <a-col :span="8">
            <PermissionButton permission="school:manager:search">
              <a-input
                v-model:value="searchForm.realName"
                placeholder="搜索管理员昵称/真实姓名"
                allow-clear
                @pressEnter="handleSearch"
              >
                <template #suffix>
                  <search-outlined />
                </template>
              </a-input>
            </PermissionButton>
          </a-col>

          <a-col :span="8" class="text-right">
            <a-space>
              <a-button @click="handleSearch">
                <search-outlined />
                搜索
              </a-button>

              <a-button @click="handleReset">
                <redo-outlined />
                重置
              </a-button>

              <PermissionButton permission="school:manager:add">
                <a-button type="primary" @click="handleAdd">
                  <plus-outlined />
                  新增管理员
                </a-button>
              </PermissionButton>
            </a-space>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 管理员列表 -->
    <div class="table-section">
      <a-card :bordered="false">
        <PermissionButton permission="school:manager:list">
          <a-table
            :columns="columns"
            :data-source="adminList"
            :pagination="paginationConfig"
            :loading="loading"
            row-key="id"
            :scroll="{ x: 980 }"
            @change="handleTableChange"
          >
            <!-- 序号列 -->
            <template #index="{ index }">
              {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
            </template>

            <!-- 头像列 -->
            <template #avatar="{ record }">
              <a-avatar :size="40" :src="record.avatar">
                {{ (record.realName || record.nickName)?.[0] || '管' }}
              </a-avatar>
            </template>

            <!-- 昵称列 -->
            <template #nickName="{ record }">
              <div class="nickname-cell">
                <span class="name">{{ record.nickName || '未知用户' }}</span>
              </div>
            </template>

            <!-- 真实姓名列 -->
            <template #realName="{ record }">
              <div class="realname-cell">
                <span class="name">{{ record.realName || '-' }}</span>
              </div>
            </template>

            <!-- 学校信息列 -->
            <template #schoolInfo="{ record }">
              <div class="school-info-cell">
                <a-typography-text
                  :content="record.schoolInfo || '暂无信息'"
                  :ellipsis="{ tooltip: true }"
                  class="school-info-text"
                >
                  <a-tag v-if="record.schoolInfo" color="blue" class="school-info-tag">
                    <bank-outlined />
                    {{ record.schoolInfo }}
                  </a-tag>
                  <span v-else class="no-school-info">暂无信息</span>
                </a-typography-text>
              </div>
            </template>

            <!-- 绑定时间列 -->
            <template #createdTime="{ record }">
              <span>{{ formatDate(record.createdTime) }}</span>
            </template>

            <!-- 操作列 -->
            <template #action="{ record }">
              <a-space>
                <PermissionButton permission="school:manager:edit">
                  <a-button type="link" size="small" @click="handleEdit(record)"> 编辑 </a-button>
                </PermissionButton>

                <PermissionButton permission="school:manager:delete">
                  <a-popconfirm
                    title="确定要删除这个管理员吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="handleDelete(record)"
                  >
                    <a-button type="link" size="small" danger> 删除 </a-button>
                  </a-popconfirm>
                </PermissionButton>
              </a-space>
            </template>
          </a-table>
        </PermissionButton>
      </a-card>
    </div>

    <!-- 新增管理员弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="新增学校管理员"
      width="600px"
      :confirm-loading="confirmLoading"
      @ok="handleAddConfirm"
      @cancel="handleAddCancel"
    >
      <div class="add-admin-modal">
        <!-- 学校选择区域 -->
        <div class="school-section">
          <a-form layout="vertical">
            <a-form-item
              label="选择学校"
              :validate-status="selectedSchoolId ? 'success' : 'error'"
              :help="selectedSchoolId ? '' : '请选择要添加管理员的学校'"
            >
              <a-select
                v-model:value="selectedSchoolId"
                placeholder="请选择学校"
                style="width: 100%"
                show-search
                :filter-option="filterSchoolOption"
              >
                <a-select-option v-for="school in schoolList" :key="school.id" :value="school.id">
                  {{ school.schoolName }}-{{ school.campuses }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>

        <!-- 真实姓名输入区域 -->
        <div class="realname-section">
          <a-form layout="vertical">
            <a-form-item
              label="真实姓名"
              :validate-status="realNameValidateStatus"
              :help="realNameErrorMessage"
            >
              <a-input
                v-model:value="realNameInput"
                placeholder="请输入管理员真实姓名"
                :maxlength="20"
                @input="handleRealNameInput"
              />
            </a-form-item>
          </a-form>
        </div>

        <!-- 手机号搜索区域 -->
        <div class="search-section">
          <a-form layout="vertical">
            <a-form-item
              label="手机号码"
              :validate-status="phoneValidateStatus"
              :help="phoneErrorMessage"
            >
              <a-input-group compact>
                <a-input
                  v-model:value="searchPhone"
                  placeholder="请输入完整的11位手机号码"
                  style="width: calc(100% - 100px)"
                  :maxlength="11"
                  @input="handlePhoneInput"
                  @pressEnter="handleSearchUser"
                />
                <a-button
                  type="primary"
                  :loading="searchLoading"
                  :disabled="!isPhoneValid"
                  @click="handleSearchUser"
                >
                  搜索用户
                </a-button>
              </a-input-group>
            </a-form-item>
          </a-form>
        </div>

        <!-- 用户信息展示区域 -->
        <div v-if="searchedUser" class="user-section">
          <div class="section-title">
            <h4>用户信息</h4>
          </div>
          <!-- 用户信息卡片 -->
          <a-card :bordered="false" class="user-info-card">
            <div class="user-header">
              <a-avatar
                :size="64"
                :src="searchedUser.avatar || searchedUser.defaultAvatar"
                class="user-avatar"
              >
                {{ searchedUser.nickName?.[0] || searchedUser.defaultNickName?.[0] || '?' }}
              </a-avatar>
              <div class="user-basic">
                <h4 class="user-name">
                  {{ searchedUser.nickName || searchedUser.defaultNickName || '未知用户' }}
                </h4>
                <a-tag
                  :color="searchedUser.userStatus === 'normal' ? 'green' : 'red'"
                  class="user-status"
                >
                  {{ searchedUser.userStatus === 'normal' ? '正常' : '封禁' }}
                </a-tag>
              </div>
            </div>

            <a-divider style="margin: 16px 0" />

            <div class="user-details">
              <div v-if="searchedUser.phone" class="detail-item">
                <span class="label">📱 手机号：</span>
                <span class="value">{{ searchedUser.phone }}</span>
              </div>

              <div v-if="searchedUser.email" class="detail-item">
                <span class="label">📧 邮箱：</span>
                <span class="value">{{ searchedUser.email }}</span>
              </div>

              <div v-if="searchedUser.sex" class="detail-item">
                <span class="label">👤 性别：</span>
                <span class="value">{{ searchedUser.sex === 1 ? '男' : '女' }}</span>
              </div>

              <div v-if="searchedUser.grade" class="detail-item">
                <span class="label">🎓 年级：</span>
                <span class="value">{{ searchedUser.grade }}</span>
              </div>

              <div v-if="searchedUser.studentId" class="detail-item">
                <span class="label">🆔 学号：</span>
                <span class="value">{{ searchedUser.studentId }}</span>
              </div>

              <div v-if="searchedUser.userType" class="detail-item">
                <span class="label">👥 用户类型：</span>
                <span class="value">
                  {{ searchedUser.userType === 'wechat' ? '微信用户' : '匿名用户' }}
                </span>
              </div>
            </div>
          </a-card>
        </div>

        <!-- 空状态 -->
        <div v-else-if="hasSearched && !searchLoading" class="empty-state">
          <a-empty
            description="未找到该手机号对应的用户信息"
            :image="Empty.PRESENTED_IMAGE_SIMPLE"
          />
        </div>
      </div>
    </a-modal>

    <!-- 编辑管理员弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑学校管理员"
      width="500px"
      :confirm-loading="editConfirmLoading"
      @ok="handleEditConfirm"
      @cancel="handleEditCancel"
    >
      <div class="edit-admin-modal">
        <a-form layout="vertical">
          <a-form-item
            label="真实姓名"
            :validate-status="editRealNameValidateStatus"
            :help="editRealNameErrorMessage"
          >
            <a-input
              v-model:value="editRealNameInput"
              placeholder="请输入管理员真实姓名"
              :maxlength="20"
              @input="handleEditRealNameInput"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { message, Empty } from 'ant-design-vue'
import type { TableColumnType, TableProps } from 'ant-design-vue'
import { SearchOutlined, PlusOutlined, RedoOutlined, BankOutlined } from '@ant-design/icons-vue'
import { schoolAdminService } from '../../../api/schoolAdmin'
import { schoolService } from '../../../api/school'
import { UserService } from '../../../api/user'
import { debounce } from '../../../utils/debounce'
import PermissionButton from '../../../components/PermissionButton.vue'
import type {
  SchoolAdmin,
  SchoolAdminPageParams,
  School,
  UserByPhoneResponse,
} from '../../../types'

// 响应式数据
const loading = ref(false)
const adminList = ref<SchoolAdmin[]>([])
const schoolList = ref<School[]>([])
const addModalVisible = ref(false)
const editModalVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  schoolId: undefined as number | undefined,
  realName: '',
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
})

// 新增管理员弹窗相关
const searchPhone = ref('')
const searchLoading = ref(false)
const confirmLoading = ref(false)
const searchedUser = ref<UserByPhoneResponse | null>(null)
const hasSearched = ref(false)
const selectedSchoolId = ref<number | undefined>(undefined)
const realNameInput = ref('')

// 编辑管理员弹窗相关
const editConfirmLoading = ref(false)
const editRealNameInput = ref('')
const editingRecord = ref<SchoolAdmin | null>(null)

// 表格列配置
const columns: TableColumnType[] = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    slots: { customRender: 'index' },
  },
  {
    title: '头像',
    key: 'avatar',
    width: 80,
    align: 'center',
    slots: { customRender: 'avatar' },
  },
  {
    title: '昵称',
    dataIndex: 'nickName',
    key: 'nickName',
    width: 120,
    slots: { customRender: 'nickName' },
  },
  {
    title: '真实姓名',
    dataIndex: 'realName',
    key: 'realName',
    width: 100,
    slots: { customRender: 'realName' },
  },
  {
    title: '学校信息',
    dataIndex: 'schoolInfo',
    key: 'schoolInfo',
    width: 180,
    ellipsis: true,
    slots: { customRender: 'schoolInfo' },
  },
  {
    title: '绑定时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 160,
    slots: { customRender: 'createdTime' },
  },
  {
    title: '操作',
    key: 'action',
    width: 140,
    align: 'center',
    fixed: 'right',
    slots: { customRender: 'action' },
  },
]

// 分页配置
const paginationConfig = computed(() => ({
  current: pagination.current,
  pageSize: pagination.pageSize,
  total: pagination.total,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100'],
}))

// 手机号验证
const phoneValidateStatus = computed(() => {
  if (!searchPhone.value) return ''
  return isPhoneValid.value ? 'success' : 'error'
})

const phoneErrorMessage = computed(() => {
  if (!searchPhone.value) return ''
  return isPhoneValid.value ? '' : '请输入正确的11位手机号码'
})

const isPhoneValid = computed(() => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(searchPhone.value)
})

// 真实姓名验证（新增）
const realNameValidateStatus = computed(() => {
  if (!realNameInput.value) return 'error'
  return realNameInput.value.trim().length >= 2 ? 'success' : 'error'
})

const realNameErrorMessage = computed(() => {
  if (!realNameInput.value) return '请输入真实姓名'
  return realNameInput.value.trim().length >= 2 ? '' : '真实姓名至少2个字符'
})

const isRealNameValid = computed(() => {
  return realNameInput.value.trim().length >= 2
})

// 真实姓名验证（编辑）
const editRealNameValidateStatus = computed(() => {
  if (!editRealNameInput.value) return 'error'
  return editRealNameInput.value.trim().length >= 2 ? 'success' : 'error'
})

const editRealNameErrorMessage = computed(() => {
  if (!editRealNameInput.value) return '请输入真实姓名'
  return editRealNameInput.value.trim().length >= 2 ? '' : '真实姓名至少2个字符'
})

const isEditRealNameValid = computed(() => {
  return editRealNameInput.value.trim().length >= 2
})

// 初始化数据
onMounted(() => {
  loadSchoolList()
  loadAdminList() // 页面加载后直接加载所有管理员列表
})

// 加载学校列表
const loadSchoolList = async () => {
  try {
    const schoolPageResult = await schoolService.getSchoolPage({
      page: 1,
      pageSize: 1000, // 获取所有学校
      schoolStatus: 'active', // 只获取激活的学校
    })
    schoolList.value = schoolPageResult.result
  } catch (error) {
    console.error('加载学校列表失败:', error)
    message.error('加载学校列表失败')
  }
}

// 加载管理员列表 - 修改为支持加载所有管理员
const loadAdminList = async () => {
  try {
    loading.value = true

    const params: SchoolAdminPageParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      isDeleted: 0,
      realName: searchForm.realName,
    }

    // 如果选择了学校，则按学校过滤
    if (searchForm.schoolId) {
      params.schoolId = searchForm.schoolId
    }

    const result = await schoolAdminService.getSchoolAdminPage(params)
    adminList.value = result.result
    pagination.total = result.total
  } catch (error) {
    console.error('加载管理员列表失败:', error)
    message.error('加载管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 学校选择变化 - 不自动搜索，等待用户点击搜索按钮
const handleSchoolChange = () => {
  // 移除自动搜索逻辑
}

// 搜索学校选项过滤 - 优化为按学校-校区格式搜索
const filterSchoolOption = (input: string, option: any) => {
  const schoolText = option.children || ''
  return schoolText.toLowerCase().includes(input.toLowerCase())
}

// 手动触发搜索
const handleSearch = () => {
  pagination.current = 1
  loadAdminList()
}

// 重置搜索
const handleReset = () => {
  searchForm.schoolId = undefined
  searchForm.realName = ''
  pagination.current = 1
  loadAdminList()
}

// 格式化日期
const formatDate = (dateString: string): string => {
  if (!dateString) return '-'

  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  } catch (error) {
    return dateString
  }
}

// 表格变化处理
const handleTableChange: TableProps['onChange'] = (paginationInfo) => {
  if (paginationInfo) {
    pagination.current = paginationInfo.current || 1
    pagination.pageSize = paginationInfo.pageSize || 20
    loadAdminList()
  }
}

// 新增管理员 - 移除学校选择限制
const handleAdd = () => {
  addModalVisible.value = true
}

// 防抖处理手机号输入
const handlePhoneInput = debounce(() => {
  // 如果手机号发生变化，清除之前的搜索结果
  if (searchedUser.value) {
    searchedUser.value = null
    hasSearched.value = false
  }
}, 300)

// 处理真实姓名输入
const handleRealNameInput = () => {
  // 触发验证状态更新
}

// 处理编辑真实姓名输入
const handleEditRealNameInput = () => {
  // 触发验证状态更新
}

// 搜索用户
const handleSearchUser = async () => {
  if (!isPhoneValid.value) {
    message.warning('请输入正确的11位手机号码')
    return
  }

  try {
    searchLoading.value = true
    hasSearched.value = true
    searchedUser.value = null

    const userInfo = await UserService.getUserByPhone(searchPhone.value)
    searchedUser.value = userInfo

    // 检查用户状态
    if (userInfo.userStatus !== 'normal') {
      message.warning('该用户当前状态为封禁，无法设置为管理员')
    }
  } catch (error: any) {
    console.error('搜索用户失败:', error)

    // 根据错误信息给出友好提示
    if (error.message?.includes('404') || error.message?.includes('not found')) {
      message.warning('未找到该手机号对应的用户')
    } else {
      message.error('搜索用户失败，请稍后重试')
    }
  } finally {
    searchLoading.value = false
  }
}

// 确认新增管理员
const handleAddConfirm = async () => {
  if (!selectedSchoolId.value) {
    message.warning('请先选择要添加管理员的学校')
    return
  }

  if (!isRealNameValid.value) {
    message.warning('请输入正确的真实姓名')
    return
  }

  if (!searchedUser.value) {
    message.warning('请先搜索并选择要添加的用户')
    return
  }

  if (searchedUser.value.userStatus !== 'normal') {
    message.error('该用户当前状态为封禁，无法设置为管理员')
    return
  }

  try {
    confirmLoading.value = true

    await schoolAdminService.createSchoolAdmin({
      schoolId: selectedSchoolId.value,
      adminId: searchedUser.value.id,
      realName: realNameInput.value.trim(),
    })

    message.success('新增管理员成功')
    addModalVisible.value = false
    resetAddModal()
    loadAdminList() // 刷新列表
  } catch (error: any) {
    console.error('新增管理员失败:', error)

    // 根据错误信息给出友好提示
    if (error.message?.includes('已存在')) {
      message.error('该用户已经是此学校的管理员')
    } else {
      message.error('新增管理员失败，请稍后重试')
    }
  } finally {
    confirmLoading.value = false
  }
}

// 取消新增管理员
const handleAddCancel = () => {
  resetAddModal()
  addModalVisible.value = false
}

// 重置新增弹窗
const resetAddModal = () => {
  searchPhone.value = ''
  searchedUser.value = null
  hasSearched.value = false
  searchLoading.value = false
  confirmLoading.value = false
  selectedSchoolId.value = undefined
  realNameInput.value = ''
}

// 编辑管理员
const handleEdit = (record: SchoolAdmin) => {
  editingRecord.value = record
  editRealNameInput.value = record.realName || ''
  editModalVisible.value = true
}

// 确认编辑管理员
const handleEditConfirm = async () => {
  if (!editingRecord.value) {
    message.error('编辑数据异常')
    return
  }

  if (!isEditRealNameValid.value) {
    message.warning('请输入正确的真实姓名')
    return
  }

  try {
    editConfirmLoading.value = true

    await schoolAdminService.updateSchoolAdmin({
      id: editingRecord.value.id,
      realName: editRealNameInput.value.trim(),
    })

    message.success('编辑管理员成功')
    editModalVisible.value = false
    resetEditModal()
    loadAdminList() // 刷新列表
  } catch (error: any) {
    console.error('编辑管理员失败:', error)
    message.error('编辑管理员失败，请稍后重试')
  } finally {
    editConfirmLoading.value = false
  }
}

// 取消编辑管理员
const handleEditCancel = () => {
  resetEditModal()
  editModalVisible.value = false
}

// 重置编辑弹窗
const resetEditModal = () => {
  editRealNameInput.value = ''
  editingRecord.value = null
  editConfirmLoading.value = false
}

// 删除管理员
const handleDelete = async (record: SchoolAdmin) => {
  try {
    await schoolAdminService.deleteSchoolAdmin(record.id)
    message.success('删除管理员成功')
    loadAdminList() // 刷新列表
  } catch (error) {
    console.error('删除管理员失败:', error)
    message.error('删除管理员失败')
  }
}
</script>

<style scoped lang="scss">
.school-manager-page {
  padding: 24px;

  .search-section {
    margin-bottom: 16px;

    .text-right {
      text-align: right;
    }
  }

  .table-section {
    .ant-card {
      min-height: 400px;
    }

    .nickname-cell,
    .realname-cell {
      .name {
        font-weight: 500;
        color: #262626;
      }
    }

    .school-info-cell {
      .school-info-tag {
        margin: 0;
        font-size: 12px;
        border-radius: 4px;
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        line-height: 20px;
        font-weight: 500;
        max-width: 160px;

        :deep(.anticon) {
          margin-right: 4px;
          font-size: 12px;
        }
      }

      .no-school-info {
        color: #999;
        font-style: italic;
        font-size: 12px;
      }

      .school-info-text {
        font-size: 13px;
      }
    }
  }
}

// 新增管理员弹窗样式
.add-admin-modal {
  .school-section {
    margin-bottom: 24px;
  }

  .realname-section {
    margin-bottom: 24px;
  }

  .search-section {
    margin-bottom: 24px;
  }

  .user-section {
    .section-title {
      margin-bottom: 16px;

      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #262626;
      }
    }
  }

  .empty-state {
    padding: 40px 0;
    text-align: center;
  }
}

// 编辑管理员弹窗样式
.edit-admin-modal {
  padding: 20px 0;
}

// 用户信息卡片样式
.user-info-card {
  .user-header {
    display: flex;
    align-items: center;
    gap: 16px;

    .user-avatar {
      flex-shrink: 0;
    }

    .user-basic {
      flex: 1;

      .user-name {
        margin: 0 0 8px 0;
        font-size: 18px;
        font-weight: 600;
        color: #262626;
      }

      .user-status {
        font-size: 12px;
      }
    }
  }

  .user-details {
    .detail-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 100px;
        font-weight: 500;
        color: #595959;
        flex-shrink: 0;
      }

      .value {
        color: #262626;
        word-break: break-all;
      }
    }
  }
}

// 表格样式优化
:deep(.ant-table) {
  .ant-table-thead > tr > th {
    background: #fafafa;
    font-weight: 600;
  }

  .ant-table-tbody > tr:hover > td {
    background: #f5f5f5;
  }
}

// 输入框样式优化
:deep(.ant-input-group) {
  .ant-input {
    border-radius: 6px 0 0 6px;
  }

  .ant-btn {
    border-radius: 0 6px 6px 0;
    height: 32px;
  }
}

// 响应式布局
@media (max-width: 768px) {
  .school-manager-page {
    padding: 16px;

    .search-section {
      :deep(.ant-row) {
        flex-direction: column;
        gap: 16px;

        .ant-col {
          width: 100% !important;
          flex: none !important;

          &.text-right {
            text-align: left;
          }
        }
      }
    }
  }
}
</style>